package top.codedance.iotp.server.net.handle.subhandle.controller.http.sync;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.entity.DeviceEntity;
import top.codedance.iotp.server.ServerApplication;
import top.codedance.iotp.server.net.handle.subhandle.controller.AdapterController;
import top.codedance.iotp.server.net.handle.util.DeviceService;
import org.apache.log4j.Logger;

import java.util.Date;

public class DeviceAddController extends AdapterController {

    private static Logger logger = ServerApplication.getLogger(DeviceAddController.class);

    public String doSubHandler(JSONObject body) {
        try {
            if (!adminVerification()) {
                return response403("No access");
            }
            JSONArray resultArr = new JSONArray();
            JSONArray objects = body.getJSONArray("devices");
            JSONObject jsonObject;
            DeviceEntity deviceEntity;
            DeviceEntity device;
            for (int i = 0; i < objects.size(); i++) {
                jsonObject = objects.getJSONObject(i);
                deviceEntity = new DeviceEntity();
                if(jsonObject.containsKey("id")){
                    deviceEntity.setId(jsonObject.getInteger("id"));
                }
                deviceEntity.setDeviceId(jsonObject.getString("deviceId"));
                deviceEntity.setUnitName(jsonObject.getString("unitName"));
                deviceEntity.setRegisteTime(new Date().toString());
                DeviceService.add(deviceEntity);
                device = DeviceService.getDevice(deviceEntity.getDeviceId());
                resultArr.add(device);
            }
            ServerApplication.initDeviciesCache();
            return okResponse(resultArr.toJSONString());
        } catch (Exception e) {
            return response500("Programe exception");
        }
    }
}
